#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
音频播放模块 - Flask版本
"""

import pygame
import time
import os
import threading
from config import AUDIO_DIR, DEFAULT_VOLUME

class AudioPlayer:
    def __init__(self):
        """初始化音频播放器"""
        self.initialized = False
        self.current_volume = DEFAULT_VOLUME
        self.is_playing = False
        self.play_thread = None
        self._init_mixer()
    
    def _init_mixer(self):
        """初始化pygame mixer"""
        try:
            # 初始化pygame mixer
            pygame.mixer.pre_init(frequency=22050, size=-16, channels=2, buffer=512)
            pygame.mixer.init()
            pygame.mixer.music.set_volume(self.current_volume / 100.0)
            self.initialized = True
            print("音频播放器初始化成功")
        except Exception as e:
            print(f"音频播放器初始化失败: {e}")
            self.initialized = False
    
    def play_audio(self, file_path, volume=None):
        """
        播放音频文件（非阻塞方式）
        
        Args:
            file_path (str): 音频文件路径
            volume (int, optional): 音量大小(0-100)
            
        Returns:
            bool: 播放是否成功
        """
        try:
            # 检查pygame mixer是否已初始化
            if not self.initialized:
                print("音频播放器未初始化")
                return False
            
            # 如果已经在播放，先停止
            if self.is_playing:
                self.stop_audio()
            
            # 如果指定了音量，则使用指定音量
            if volume is not None:
                pygame.mixer.music.set_volume(volume / 100.0)
            else:
                pygame.mixer.music.set_volume(self.current_volume / 100.0)
            
            # 检查文件是否存在
            if not os.path.exists(file_path):
                print(f"音频文件不存在: {file_path}")
                return False
            
            # 在新线程中播放音频
            self.play_thread = threading.Thread(target=self._play_audio_thread, args=(file_path,))
            self.play_thread.daemon = True
            self.play_thread.start()
                
            return True
        except Exception as e:
            print(f"播放音频时出错: {e}")
            return False
    
    def _play_audio_thread(self, file_path):
        """在独立线程中播放音频"""
        try:
            self.is_playing = True
            # 播放音频
            pygame.mixer.music.load(file_path)
            pygame.mixer.music.play()
            
            # 等待播放完成
            while pygame.mixer.music.get_busy() and self.is_playing:
                time.sleep(0.1)
                
            self.is_playing = False
        except Exception as e:
            print(f"播放音频时出错: {e}")
            self.is_playing = False
    
    def stop_audio(self):
        """停止当前播放的音频"""
        try:
            self.is_playing = False
            pygame.mixer.music.stop()
            if self.play_thread and self.play_thread.is_alive():
                self.play_thread.join(timeout=1)  # 等待线程结束，最多等待1秒
        except Exception as e:
            print(f"停止音频播放时出错: {e}")
    
    def set_volume(self, volume):
        """
        设置音量
        
        Args:
            volume (int): 音量大小(0-100)
        """
        try:
            if 0 <= volume <= 100:
                self.current_volume = volume
                if self.initialized:
                    pygame.mixer.music.set_volume(volume / 100.0)
        except Exception as e:
            print(f"设置音量时出错: {e}")
    
    def get_volume(self):
        """获取当前音量"""
        return self.current_volume

# 全局音频播放器实例
audio_player = AudioPlayer()

def main():
    # 测试代码
    player = AudioPlayer()
    print("音频播放模块测试")
    
if __name__ == "__main__":
    main()